<script setup lang="ts">
import { ref, reactive } from 'vue'
import { reqUserInfo, reqCertationType, reqUserCertation } from '@/api/user.ts'
import type { UseringoResponseData, CertationTypeResponseData, CertationType } from '@/api/type.ts'
import { Plus } from '@element-plus/icons-vue'
const userInfo = ref<any>({})
const arrType = ref<CertationType[]>([])
const certificateKeyVal = ref<Record<string, string>>({})
async function getInfo() {
    const res2: CertationTypeResponseData = await reqCertationType()
    // console.log(res2)
    arrType.value = res2.data
    for (let i = 0; i < arrType.value.length; i++) {
        certificateKeyVal.value[arrType.value[i].value] = arrType.value[i].name
    }
    // 
    const res1: UseringoResponseData = await reqUserInfo()
    // console.log(res1)
    userInfo.value = res1.data

}
getInfo()

const formRef = ref()

const FormData = reactive({
    name: '',
    certificatesNo: "",
    certificatesType: "",
    certificatesUrl: "",
})
//证件号码的校验方法
const validatorNo = (rule: any, value: any, callBack: any) => {
    let sfz = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
    let hkb = /^\d{9}$/;
    if (sfz.test(value) || hkb.test(value)) {
        callBack();
    } else {
        callBack(new Error("请输入正确的身份证或者户口本的号码"));
    }
};
const formRules = {
    name: [
        { required: true, message: '必填' }
    ],
    certificatesNo: [
        { required: true, validator: validatorNo },
    ],
    certificatesType: [
        { required: true, message: '必填' }
    ],
    certificatesUrl: [
        { required: true, message: '必填' }
    ]
}


const submitForm = (formEl: any) => {
    if (!formEl) return
    formEl.validate(async (valid: any) => {
        if (valid) {
            // console.log('submit!')
            // 调用实名认证接口
            await reqUserCertation(FormData)
            getInfo()

        } else {
            console.log('error submit!')
        }
    })
}

const resetForm = (formEl: any) => {
    if (!formEl) return
    formEl.resetFields()
}

// const imageUrl = ref('')

const handleSuccess = (response: any, uploadFile: any) => {
    // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    FormData.certificatesUrl = response.data;

}

const beforeAvatarUpload = (rawFile: any) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}

</script>

<template>
    <div class="certification-container">
        <!-- authStatus==1 已实名认证 -->
        <el-descriptions v-if="userInfo.authStatus === 1" title="实名信息" :column="1" border label-width="150px">
            <template #extra>
                <p>完成实名认证后，即可享受更多服务，获得更多权益。</p>
            </template>
            <el-descriptions-item label="用户姓名">{{ userInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="证件类型">{{ certificateKeyVal[userInfo.certificatesType]
                }}</el-descriptions-item>
            <el-descriptions-item label="证件号码">{{ userInfo.certificatesNo }}</el-descriptions-item>
        </el-descriptions>
        <!-- authStatus==0 未实名认证 -->
        <h3 style="text-align: center;font-size: 16px;margin: 20px 0;">完成/修改实名认证信息</h3>
        <el-form ref="formRef" style="width: 500px;margin: 10px auto;" :model="FormData" label-width="auto"
            class="demo-ruleForm" :rules="formRules">
            <el-form-item label="用户姓名" prop="name">
                <el-input v-model.number="FormData.name" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item label="证件类型" prop="certificatesType">
                <el-select v-model="FormData.certificatesType">
                    <el-option v-for="item in arrType" :key="item.value" :label="item.name" :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="certificatesNo">
                <el-input v-model.number="FormData.certificatesNo" type="text" autocomplete="off" />
            </el-form-item>
            <el-form-item label="证件照片" prop="certificatesUrl">
                <el-upload class="avatar-uploader"
                    action="http://syt.atguigu.cn/api/oss/file/fileUpload?fileHost=userAuah" :show-file-list="false"
                    :on-success="handleSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="FormData.certificatesUrl" :src="FormData.certificatesUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                    <div class="el-upload__tip" slot="tip" style="margin-left: 20px;">
                        只支持 JPG/PNG 文件，大小不超过 500kb
                    </div>
                </el-upload>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
                <el-button @click="resetForm(formRef)">重写</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>

<style scoped lang="scss">
.certification-container {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    :deep(.el-descriptions) {
        margin: 20px;

        .el-descriptions__title {
            font-weight: normal;

        }
    }
}

.el-form-item__content {
    justify-content: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    border: 1px solid var(--border-color);
}
</style>